<?php
/**
 * Created by jinqiang on 2024/7/24 11:51.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Om;


use App\Http\Models\Mysql\SsyJstPurchaseinOrderTable;
use App\Http\Models\Mysql\SsyJyProductListTable;
use App\Http\Models\Mysql\SsyPlatformSiteSkuProportionTable;
use App\Http\Models\Mysql\SsyPlatformSiteTable;
use App\Http\Models\Mysql\SsyProcessingListTable;
use App\Http\Repository\OmsRepository;
use Illuminate\Support\Facades\DB;

class InventoryService
{
    public function search($param)
    {
        $field = ["id","type_no","product_name","product_code","a_parts","purchase_qty","img","arrivaldate","arrivaldate_title","createtime","last_kx_updatetime"];
        $conn = (new SsyJyProductListTable())->select($field);
        if($param['type_no'] ?? ""){
            $conn = $conn->where('type_no', $param['type_no']);
        }
        if($param['product_code'] ?? ""){
            $conn = $conn->where('product_code', "like", $param['product_code']."%");
        }
        if($param['type_name'] ?? ""){
            $conn = $conn->where('product_name', 'like', "%".$param['type_name']."%");
        }
        $subjects = array_column(config("scm.subject"), null, 'is_subject');
        $isSubject = "kz";
        if($param['is_subject'] ?? ""){
            $isSubject = $param['is_subject'];
        }
        $virtualWarehouseCode = $subjects[$isSubject]['virtual_warehouse_code'];
        $brandCode = $subjects[$isSubject]['brand_code_jy'];
        $conn = $conn->where('brand_code', $brandCode);
        $res = $conn->orderBy("id", "desc")->orderBy("product_code", "desc")->paginate((Int)$param['limit'], "*", "page", (Int)$param['page'])->toArray();
        list($list, $total) = [$res['data'], $res['total']];
        if(empty($list)){
            return ['data' => [], 'total' => 0];
        }
        //获取该款号是否单独设置比例分配
        $typeNos = array_column($list, 'type_no');
        $skuProportion = [];
        $skuProportionList = (new SsyPlatformSiteSkuProportionTable())->whereIn('type_no', $typeNos)->get()->toArray();
        foreach ($skuProportionList as $item){
            $skuProportion[$item['type_no']][] = $item;
        }
        //后台默认比例 2童装 1成人
        $config = (new SsyPlatformSiteTable())->get()->toArray();//后台配置
        $proportionConfig = [];
        foreach ($config as $item){
            $proportionConfig[$item['types']][] = $item;
        }
        //获取巨益可销数
        $omsRes = OmsRepository::searchNum($virtualWarehouseCode, array_column($list, 'product_code'));
        $omsList = $omsRes['stockInfoList'] ?? [];
        $omsSellableQuantity =  array_column($omsList, "sellableQuantity", "skuCode");
        //获取所有未加工单 f_status 0 未完结进行中
        $processingList = (new SsyProcessingListTable())->where('f_status', 0)->where('status', 1)->whereIn('sku_code', array_column($list, 'product_code'))
            ->get(["processing_code","sku_code","po_id","bao_number","num"])->toArray();
        $processingMap = [];
        foreach($processingList as $item){
            $processingMap[$item['sku_code']][] = $item;
        }
        foreach ($list as $key => $val){
            //未完结的列表
            $processingCodeList = $processingMap[$val['product_code']] ?? [];
            $processingCodes = array_column($processingCodeList, 'processing_code');
            //回货总入库数
            $purchase_qtys = 0;
            if(!empty($processingCodes)){
                $purchase_qtys = (new SsyJstPurchaseinOrderTable())->where('sku_id', $val['product_code'])->whereIn('processing_code', $processingCodes)
                    ->where('po_id', 'like', 'PNO%')->sum('qty');
            }
            //总下单数
            $pronum = array_sum(array_column($processingCodeList, 'num'));
            //报次数
            $bao_number = array_sum(array_column($processingCodeList, 'bao_number'));
            //巨益可销售数据
            $val['use_num'] = $omsSellableQuantity[$val['product_code']] ?? 0;
            //总预售数
            $purchase_qty=0;
            if($pronum > $purchase_qtys){
                $purchase_qty=$pronum-$purchase_qtys-$bao_number; //总预售数=总加工单数-总入库数-报次数
            }
            $batch_jsts=0;
            if($purchase_qtys){
                $batch_jsts = $purchase_qtys;
            }
            if($pronum>0) { //批次加工单数大于0
                //$batch_pro = $batch_pronum+$bat_zc_pronum-$batch_jsts-$batch_processing['bao_number']; //=批次总加工单数+批次增裁数-批次总入库数 - 批次报次数
                $batch_pro = $pronum-$batch_jsts;
            }else{
                $batch_pro=0;
            }
            $list[$key]['amount']=$pronum-$bao_number;//总在途数
            $list[$key]['bao_number']=$bao_number;
            if($val['use_num']>=0){
                $list[$key]['yushou']= floor($purchase_qty);
                $list[$key]['xianhu']  = $val['use_num'];
            }else{
                $list[$key]['yushou'] = floor($purchase_qty+$val['use_num']);
                $list[$key]['xianhu']  =0;
            }
            $list[$key]['count']=floor($purchase_qty+$val['use_num']);//总数 = (总预售数=总加工单数-总入库数-报次数) + 可销数

            //2童装 1成人
            $str=substr($val['type_no'],0,3);
            $config = $proportionConfig[in_array($str, ["STZ", "STP"]) ? 2 : 1];
            if(isset($skuProportion[$val['type_no']])){
                $proportion = array_column($skuProportion[$val['type_no']], 'proportion', 'site_id');
            }else{
                $proportion = array_column($config, 'proportion', 'id');
            }
            $sount=0;
            foreach ($config as $v){
                $proportionddd = $proportion[$v['id']]/100;
                $list[$key][$v['marks']]['title'] = $v['title'];
                $list[$key][$v['marks']]['logo'] = $v['logo'];
                $list[$key][$v['marks']]['zhanbi']  =$ss= floor($val['use_num']*$proportionddd);
                $sount+=$ss;
                if($val['use_num']>=0){ //SGF141732XS SGF112983PKXS
                    $list[$key][$v['marks']]['yushou']=floor($purchase_qty*$proportionddd);
                    $list[$key][$v['marks']]['xianhu']  = floor($val['use_num']*$proportionddd);
                    $list[$key][$v['marks']]['batch_yushou']=floor($batch_pro*$proportionddd);; //  =批次加工单总数+批次增裁数-批次入库数-爆次数
                }else{
                    $list[$key][$v['marks']]['yushou'] = floor(ceil($purchase_qty+$val['use_num'])*$proportionddd);
                    $list[$key][$v['marks']]['xianhu']  = 0;
                    if($batch_pro>0){
                        $list[$key][$v['marks']]['batch_yushou'] = floor(($batch_pro+$val['use_num'])*$proportionddd);
                    }else{
                        $list[$key][$v['marks']]['batch_yushou']=0;
                    }
                }
                $list[$key][$v['marks']]['proportion']='';
                $list[$key]['liu']['title']='预留';
                $list[$key]['liu']['logo']='https://ssy.13yu.com/Public/liu.png';
                $list[$key]['liu']['yuliu']=$val['use_num']-$sount;
            }
        }
        return ['data' => $list, 'total' => $total];
    }

    public function getProportion($typeNo)
    {
        $jyObj = (new SsyJyProductListTable())->where('type_no', $typeNo)->first();
        if(empty($jyObj)){
            return ['code' => -1, 'msg' => '款号错误'];
        }
        $proportionList = (new SsyPlatformSiteSkuProportionTable())->where('type_no', $typeNo)->get()->toArray();
        if(!empty($proportionList)){
            $platformSiteList = (new SsyPlatformSiteTable())->whereIn('id', array_column($proportionList, 'site_id'))->get()->toArray();
            $platformSiteMap = array_column($platformSiteList, null, 'id');
            foreach ($proportionList as &$item){
                $item['title'] = $platformSiteMap[$item['site_id']]['title'];
                $item['logo'] = $platformSiteMap[$item['site_id']]['logo'];
            }
            unset($item);
            return ['code' => 0, 'data' => $proportionList];
        }
        $type = substr($typeNo,0,3);
        $platformSiteList = (new SsyPlatformSiteTable())->where('types', in_array($type, ['STZ', 'STP']) ? 2 : 1)->orderBy('listorder', 'desc')->get()->toArray();
        foreach($platformSiteList as &$item){
            $item['site_id'] = $item['id'];
            $item['type_no'] = $typeNo;
            unset($item['id']);
        }
        unset($item);
        return ['code' => 0, 'data' => $platformSiteList];
    }

    public function setProportion($data)
    {
        $data = json_decode($data, true);
        $num = 0;
        DB::beginTransaction();
        foreach($data as $item){
            $num += (Float)$item['proportion'];
            $proportionId = $item['id'] ?? "";
            if(!empty($proportionId)){
                $res = (new SsyPlatformSiteSkuProportionTable())->updateData($proportionId, ['proportion' => $item['proportion']]);
                if($res['code'] !== 0){
                    DB::rollBack();
                    return $res;
                }
            }else{
                $res = (new SsyPlatformSiteSkuProportionTable())->createData([
                    'site_id' => $item['site_id'],
                    'type_no' => $item['type_no'],
                    'proportion' => $item['proportion'],
                    'createtime' => date('Y-m-d H:i:s')
                ]);
                if($res['code'] !== 0){
                    DB::rollBack();
                    return $res;
                }
            }
        }
        if($num > 100){
            DB::rollBack();
            return ['code' => -1, 'msg' => '比例分配超过百分之百，请重新分配！'];
        }
        DB::commit();
        return ['code' => 0];
    }

    public function setArrivalDate($param)
    {
        $exist = (new SsyJyProductListTable())->where('type_no', $param['type_no'])->exists();
        if(empty($exist)){
            return ['code' => -1, 'msg' => '款号不存在'];
        }
        $data = [
            'arrivaldate' => $param['arrivaldate'],
        ];
        if($param['arrivaldate_title'] ?? ""){
            $data['arrivaldate_title'] = $param['arrivaldate_title'];
        }
        return (new SsyJyProductListTable())->updateDataWhere(['type_no' => $param['type_no']], $data);
    }
}
